import json

from django import http
from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
from django.views import View
import logging

from AJZF.scripts.data_calculate import days
from AJZF.utils.fastdfs_conf.fastdfs_storage import FastDFSStorage
from address.models import Area

from orders.models import Order

logger = logging.getLogger('django')

from AJZF.libs.response_code import RET
from houses.models import House,HouseImage,Facility


"显示已有房源"
class Houses(View):

    def get(self,request):
        user = request.user
        houses = House.objects.filter(user=user)
        house_list = []

        for house_model in houses:

            house_list.append({'address': house_model.address,
                           'area_name': house_model.area_id,
                           'ctime': house_model.update_time,
                           'house_id': house_model.id,
                           'img_url': house_model.index_image_url,
                           'order_count': house_model.order_count,
                           'price': house_model.price,
                           'room_count': house_model.room_count,
                           'title': house_model.title,
                           'user_avatar': user.avatar_url,})

        return http.JsonResponse({'data':house_list,
                                  'errmsg': 'OK', 'errno': RET.OK})

"增加新房源"
class Newhouse(View):

    def post(self,request):

        dict = json.loads(request.body.decode())

        title = dict.get('title')
        price = dict.get('price')
        area_id = dict.get('area_id')
        unit = dict.get('unit')
        address = dict.get('address')
        room_count = dict.get('room_count')
        acreage = dict.get('acreage')
        capacity = dict.get('capacity')
        beds = dict.get('beds')
        deposit = dict.get('deposit')
        min_days = dict.get('min_days')
        max_days = dict.get('max_days')
        facility = dict.get('facility')
        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds,
                    deposit, min_days, max_days, facility]):
            return http.JsonResponse({'errmsg': '缺少必传参数', 'errno': RET.PARAMERR})
        try:
            area = Area.objects.get(id=area_id)

        except Exception as e:
            return http.JsonResponse({'errmsg': 'area_id出错', 'errno': RET.DATAERR})

        try:
            room_count = int(room_count)
        except Exception as e:
            return http.JsonResponse({'errmsg': 'room_count出错', 'errno': RET.DATAERR})

        try:
            capacity = int(capacity)
        except Exception as e:
            return http.JsonResponse({'errmsg': 'capacity出错', 'errno': RET.DATAERR})

        try:
            min_days = int(min_days)
        except Exception as e:
            return http.JsonResponse({'errmsg': 'min_days出错', 'errno': RET.DATAERR})

        try:
            max_days = int(max_days)
        except Exception as e:
            return http.JsonResponse({'errmsg': 'max_days出错', 'errno': RET.DATAERR})

        try:
            house = House.objects.create(user=request.user, area=area, title=title, price=price,
                                 address=address,room_count=room_count, acreage=acreage, unit=unit,
                                 capacity=capacity,beds=beds, deposit=deposit, min_days=min_days,
                                 max_days=max_days)


            for i in facility:
                fac = Facility.objects.get(id = int(i))
                house.facilities.add(fac)
            data = {
                "house_id" : house.id
            }
            return http.JsonResponse({'errno': RET.OK, 'errmsg': "Ok","data":data})

        except Exception as e:
            return http.JsonResponse({'errno':RET.DBERR,'errmsg':'数据库问题'})

"添加图片"
class Houseimage(View):

    def post(self,request,house_id):
        house_image = request.FILES.get('house_image')
        if house_image is None:
            return http.JsonResponse({'errno': RET.NODATA, 'errmsg': '文件不存在'})
        try:
            file_id = FastDFSStorage().save('1.jpg', content=house_image)
            house_url = FastDFSStorage().url(file_id)
            house = House.objects.get(user=request.user, id=house_id)
            # 查询有没有主图片
            house_count = house.index_image_url
            print(house_count)

            if not house_count:  # 如果没有主图片
                house.index_image_url = house_url
                house.save()
            else:  # 如果有图片
                HouseImage.objects.create(house=house, url=house_url)

            return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': {"url": house_url}})

        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据库错误'})

"房源详情"
class Houseinfo(View):

    def get(self,request,house_id):

        # try:
        house_info = House.objects.get(id=house_id)
        # except Exception as e:
        #     return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据库错误'})

        comment = []
        comm = Order.objects.filter(house=house_info)
        for com in comm:
            comment.append({
                "comment": com.comment,
                "ctime": com.update_time,
                "user_name": com.user.username
            })
        facilities = []  # 设施信息id列表，如：[7, 8]
        facilitiess = Facility.objects.filter(house=house_info.id)
        for fac in facilitiess:
            facilities.append(fac.id)

        img_urls = [house_info.index_image_url]  # 房屋图片列表
        house_image = HouseImage.objects.filter(house=house_info)
        for image in house_image:
            img_urls.append(image.url)
        house = {"acreage": house_info.acreage,
                 "address": house_info.address,
                 "beds": house_info.beds,
                 "capacity": house_info.capacity,
                 "comments": comment,
                 "deposit": house_info.deposit,
                 "facilities": facilities,
                 "hid": house_info.id,
                 "img_urls": img_urls,
                 "max_days":house_info.max_days,
                 "min_days": house_info.min_days,
                 "price": house_info.price,
                 "room_count": house_info.room_count,
                 "title": house_info.title,
                 "unit": house_info.unit,
                 "user_avatar": house_info.user.avatar_url,
                 "user_id": house_info.user.id,
                 "user_name": house_info.user.username}

        # 获取当前用户登入状态
        username = request.user.is_authenticated
        if not username:
            user_id = -1
        else:
            user_id = request.user.id


        data = {
            "house":house,
            "user_id": user_id
        }

        return http.JsonResponse({"errmsg": "OK","errno": RET.OK,"data":data})


"首页展示"
class Firstview(View):

    def get(self,request):
        houses = House.objects.all()
        First = []
        for house_model in houses:
            First.append({'house_id': house_model.id,
                          'img_url': house_model.index_image_url,
                          'title': house_model.title,})

        return http.JsonResponse({'data':First,'errmsg':'OK','errno':'0'})

"首页搜索"
class Firsts(View):

    def get(self,request):

        aid = request.GET.get("aid")#区域id
        sdtime = request.GET.get("sd")#开始日期
        edtime = request.GET.get("ed")#结束
        sort = request.GET.get("sk")#排序方式booking(订单量), price - inc(低到高), price - des(高到低)时间
        page = request.GET.get("p")#页数,不传默认为1

        if sort == 'booking':
            sort = 'order_count'
        elif sort == 'price-inc':
            sort = 'price'
        elif sort == 'price-des':
            sort = '-price'
        else:
            sort = '-update_time'

        if not page:
            page = 1

        if not aid:
            houses = House.objects.all().order_by(sort)
        else:
            houses = House.objects.filter(area_id=aid).order_by(sort)

        paginator = Paginator(houses, 3)

        try:
            house = paginator.page(page)
        except Exception as e:
            # 如果page_num不正确，默认给用户400
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据库错误'})

        # 获取列表页总页数
        total_page = paginator.num_pages



        times = days(edtime, sdtime)

        Slist = []
        for house_model in house:
            if times:
                if house_model.min_days < times and house_model.max_days > times:

                    Slist.append({'address': house_model.address,
                                  'area_name': house_model.area_id,
                                  'ctime': house_model.update_time,
                                  'house_id': house_model.id,
                                  'img_url': house_model.index_image_url,
                                  'order_count': house_model.order_count,
                                  'price': house_model.price,
                                  'room_count': house_model.room_count,
                                  'title': house_model.title,
                                  'user_avatar': house_model.user.avatar_url, })
            else:
                Slist.append({
                    'house_id': house_model.id,
                    'order_count': house_model.order_count,
                    'title': house_model.title,
                    'ctime': house_model.update_time,
                    'price': house_model.price,
                    'area_name': house_model.area.name,
                    'address': house_model.address,
                    'room_count': house_model.room_count,
                    'img_url': house_model.index_image_url,
                    'user_avatar': house_model.user.avatar_url
                })


        return http.JsonResponse({'data':{'houses':Slist,
                                          'total_page':total_page},
                                  'errmsg': '请求成功',
                                  'errno': '0'})







